package com.base.dehong.http;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.TreeMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.base.dehong.util.LogUtils;
import com.google.gson.Gson;

/**
* @author TangWenhan/YeFengyun
*/
public class GsonRequest<T> extends Request<T> {
	private final RequestCallBack<T> mListener;  
	private Gson mGson;  
	private Class<T> mClass;
	private TreeMap<String, String> mMap;
	private Type mType;
	public GsonRequest(int method, String url,TreeMap<String, String> map,Class<T> clazz,Type type,RequestCallBack<T> listener, ErrorListener elistener) {
		super(method, url, elistener);
		mGson = new Gson();  
	    mClass = clazz;
	    mMap = map;
	    mListener = listener;  
	    mType = type;
	}

	@Override
	protected void deliverResponse(T arg0) {
		 mListener.onSuccess(arg0);  
	}

	@Override
	protected Map<String, String> getParams() throws AuthFailureError {
		return mMap;
	}
	
	@Override
	protected VolleyError parseNetworkError(VolleyError volleyError) {
		LogUtils.e("parseNetworkError:"+volleyError.getMessage());
		return super.parseNetworkError(new VolleyError("网络数据获取失败!"));
	}

	@Override
	protected Response<T> parseNetworkResponse(NetworkResponse response) {
		try {  
            String jsonString = new String(response.data,  
                    HttpHeaderParser.parseCharset(response.headers));
            LogUtils.e("jsonresult", jsonString);
            JSONObject jsonObject = new JSONObject(jsonString);
            int result = jsonObject.getInt("result");
            if (result != 1) {//1为正确
            	return Response.error(new VolleyError(jsonObject.getString("msg")));  
			} else {
				if (mClass == null) {
					return  (Response<T>) Response.success(mGson.fromJson(jsonObject.getString("data"), mType),  
		                    HttpHeaderParser.parseCacheHeaders(response));  
				}else {
					return  Response.success(mGson.fromJson(jsonObject.getString("data"), mClass),  
		                    HttpHeaderParser.parseCacheHeaders(response));  
				}
			}
           
        } catch (UnsupportedEncodingException e) {
            return Response.error(new VolleyError("编码异常！"));  
        } catch (JSONException e) {
			e.printStackTrace();
			return Response.error(new VolleyError("数据解析失败！"));  
		}
	}
	
}

